#!/bin/bash

# Java Decompiler MCP Server Setup Script
# This script checks and installs required dependencies

set -e  # Exit on any error

echo "🚀 Java Decompiler MCP Server Setup"
echo "=================================="

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Function to print colored output
print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if command exists
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# Detect OS
detect_os() {
    if [[ "$OSTYPE" == "linux-gnu"* ]]; then
        if command_exists apt-get; then
            echo "ubuntu"
        elif command_exists yum; then
            echo "centos"
        elif command_exists pacman; then
            echo "arch"
        else
            echo "linux"
        fi
    elif [[ "$OSTYPE" == "darwin"* ]]; then
        echo "macos"
    elif [[ "$OSTYPE" == "msys" ]] || [[ "$OSTYPE" == "cygwin" ]]; then
        echo "windows"
    else
        echo "unknown"
    fi
}

# Install Java based on OS
install_java() {
    local os=$(detect_os)
    print_status "Installing Java for $os..."
    
    case $os in
        "ubuntu")
            sudo apt-get update
            sudo apt-get install -y openjdk-11-jdk
            ;;
        "centos")
            sudo yum install -y java-11-openjdk java-11-openjdk-devel
            ;;
        "arch")
            sudo pacman -S --noconfirm jdk11-openjdk
            ;;
        "macos")
            if command_exists brew; then
                brew install openjdk@11
                echo 'export PATH="/opt/homebrew/opt/openjdk@11/bin:$PATH"' >> ~/.zshrc
            else
                print_error "Homebrew not found. Please install Homebrew first or install Java manually."
                return 1
            fi
            ;;
        "windows")
            print_warning "Windows detected. Please install Java manually from:"
            print_warning "https://adoptium.net/download/"
            return 1
            ;;
        *)
            print_error "Unsupported OS. Please install Java 11+ manually."
            return 1
            ;;
    esac
}

# Check Java installation
check_java() {
    print_status "Checking Java installation..."
    
    if command_exists java; then
        JAVA_VERSION=$(java -version 2>&1 | head -n1 | cut -d'"' -f2)
        print_success "Java found: $JAVA_VERSION"
        
        # Check if Java version is 8 or higher
        JAVA_MAJOR=$(echo $JAVA_VERSION | cut -d'.' -f1)
        if [[ $JAVA_MAJOR -ge 8 ]] || [[ $JAVA_VERSION == 1.8* ]]; then
            print_success "Java version is compatible"
            return 0
        else
            print_warning "Java version is too old (need 8+). Current: $JAVA_VERSION"
            return 1
        fi
    else
        print_warning "Java not found"
        return 1
    fi
}

# Download and setup CFR decompiler
setup_cfr() {
    print_status "Setting up CFR decompiler..."
    
    # Create tools directory
    mkdir -p ./tools
    
    CFR_PATH="./tools/cfr.jar"
    CFR_URL="https://github.com/leibnitz27/cfr/releases/download/0.152/cfr-0.152.jar"
    
    if [[ -f "$CFR_PATH" ]]; then
        print_success "CFR already exists at $CFR_PATH"
    else
        print_status "Downloading CFR decompiler..."
        
        if command_exists curl; then
            curl -L -o "$CFR_PATH" "$CFR_URL"
        elif command_exists wget; then
            wget -O "$CFR_PATH" "$CFR_URL"
        else
            print_error "Neither curl nor wget found. Cannot download CFR."
            print_warning "Please download CFR manually from: $CFR_URL"
            print_warning "Save it as: $CFR_PATH"
            return 1
        fi
        
        if [[ -f "$CFR_PATH" ]]; then
            print_success "CFR downloaded successfully"
        else
            print_error "Failed to download CFR"
            return 1
        fi
    fi
    
    # Test CFR
    if java -jar "$CFR_PATH" --help >/dev/null 2>&1; then
        print_success "CFR is working correctly"
    else
        print_error "CFR test failed"
        return 1
    fi
    
    # Set CFR_PATH environment variable
    CFR_ABSOLUTE_PATH=$(realpath "$CFR_PATH")
    echo "export CFR_PATH=\"$CFR_ABSOLUTE_PATH\"" >> ~/.bashrc
    echo "export CFR_PATH=\"$CFR_ABSOLUTE_PATH\"" >> ~/.zshrc 2>/dev/null || true
    export CFR_PATH="$CFR_ABSOLUTE_PATH"
    
    print_success "CFR_PATH set to: $CFR_ABSOLUTE_PATH"
}

# Setup Fernflower (alternative decompiler)
setup_fernflower() {
    print_status "Setting up Fernflower decompiler (alternative)..."
    
    FERNFLOWER_PATH="./tools/fernflower.jar"
    FERNFLOWER_URL="https://github.com/fesh0r/fernflower/releases/download/dbg_20200801/fernflower.jar"
    
    if [[ -f "$FERNFLOWER_PATH" ]]; then
        print_success "Fernflower already exists"
    else
        print_status "Downloading Fernflower..."
        
        if command_exists curl; then
            curl -L -o "$FERNFLOWER_PATH" "$FERNFLOWER_URL"
        elif command_exists wget; then
            wget -O "$FERNFLOWER_PATH" "$FERNFLOWER_URL"
        else
            print_warning "Cannot download Fernflower (curl/wget not found)"
            return 1
        fi
        
        if [[ -f "$FERNFLOWER_PATH" ]]; then
            print_success "Fernflower downloaded successfully"
            
            # Set FERNFLOWER_PATH environment variable
            FERNFLOWER_ABSOLUTE_PATH=$(realpath "$FERNFLOWER_PATH")
            echo "export FERNFLOWER_PATH=\"$FERNFLOWER_ABSOLUTE_PATH\"" >> ~/.bashrc
            echo "export FERNFLOWER_PATH=\"$FERNFLOWER_ABSOLUTE_PATH\"" >> ~/.zshrc 2>/dev/null || true
            export FERNFLOWER_PATH="$FERNFLOWER_ABSOLUTE_PATH"
            
            print_success "FERNFLOWER_PATH set to: $FERNFLOWER_ABSOLUTE_PATH"
        fi
    fi
}

# Check Node.js and npm
check_node() {
    print_status "Checking Node.js and npm..."
    
    if command_exists node && command_exists npm; then
        NODE_VERSION=$(node --version)
        NPM_VERSION=$(npm --version)
        print_success "Node.js: $NODE_VERSION, npm: $NPM_VERSION"
        return 0
    else
        print_error "Node.js or npm not found. Please install Node.js first."
        return 1
    fi
}

# Install Node.js dependencies
install_dependencies() {
    print_status "Installing Node.js dependencies..."
    
    if [[ -f "package.json" ]]; then
        npm install
        print_success "Dependencies installed"
    else
        print_error "package.json not found"
        return 1
    fi
}

# Build the project
build_project() {
    print_status "Building the project..."
    
    npm run build
    print_success "Project built successfully"
}

# Create environment configuration
create_env_config() {
    print_status "Creating environment configuration..."
    
    cat > .env << EOF
# Java Decompiler MCP Server Configuration
# Auto-generated by setup script

# CFR Decompiler Path
CFR_PATH="$(realpath ./tools/cfr.jar 2>/dev/null || echo './tools/cfr.jar')"

# Fernflower Decompiler Path (alternative)
FERNFLOWER_PATH="$(realpath ./tools/fernflower.jar 2>/dev/null || echo './tools/fernflower.jar')"

# Default Maven Local Repository Path
# Uncomment and modify if you want to use a custom path
# MAVEN_LOCAL_REPOSITORY="/path/to/your/maven/repository"

# Example for Windows WSL
# MAVEN_LOCAL_REPOSITORY="/mnt/d/mavenrepository"
EOF
    
    print_success "Environment configuration created: .env"
}

# Create startup script
create_startup_script() {
    print_status "Creating startup script..."
    
    cat > start.sh << 'EOF'
#!/bin/bash

# Load environment variables
if [[ -f ".env" ]]; then
    export $(cat .env | grep -v '^#' | xargs)
fi

# Start the MCP server
echo "🚀 Starting Java Decompiler MCP Server..."
echo "CFR_PATH: $CFR_PATH"
echo "FERNFLOWER_PATH: $FERNFLOWER_PATH"
echo "MAVEN_LOCAL_REPOSITORY: $MAVEN_LOCAL_REPOSITORY"
echo "================================"

node dist/index.js
EOF
    
    chmod +x start.sh
    print_success "Startup script created: start.sh"
}

# Main setup function
main() {
    echo
    print_status "Starting setup process..."
    echo
    
    # Check Node.js first
    if ! check_node; then
        print_error "Please install Node.js and npm first, then run this script again."
        exit 1
    fi
    
    # Install npm dependencies
    if ! install_dependencies; then
        print_error "Failed to install dependencies"
        exit 1
    fi
    
    # Check/install Java
    if ! check_java; then
        print_warning "Java not found or incompatible version"
        read -p "Do you want to install Java automatically? (y/N): " -n 1 -r
        echo
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            if ! install_java; then
                print_error "Failed to install Java automatically"
                print_warning "Please install Java 8+ manually and run this script again"
                exit 1
            fi
            
            # Re-check Java after installation
            if ! check_java; then
                print_error "Java installation verification failed"
                exit 1
            fi
        else
            print_warning "Skipping Java installation. Some features may not work."
        fi
    fi
    
    # Setup CFR decompiler
    if ! setup_cfr; then
        print_error "Failed to setup CFR decompiler"
        exit 1
    fi
    
    # Setup Fernflower (optional)
    setup_fernflower  # Don't fail if this doesn't work
    
    # Build project
    if ! build_project; then
        print_error "Failed to build project"
        exit 1
    fi
    
    # Create configuration files
    create_env_config
    create_startup_script
    
    echo
    print_success "🎉 Setup completed successfully!"
    echo
    echo "📋 What was installed/configured:"
    echo "  ✅ Node.js dependencies"
    echo "  ✅ Java runtime environment"
    echo "  ✅ CFR decompiler"
    echo "  ✅ Environment configuration (.env)"
    echo "  ✅ Startup script (start.sh)"
    echo
    echo "🚀 To start the server:"
    echo "  ./start.sh"
    echo
    echo "🔧 Or run manually:"
    echo "  node dist/index.js"
    echo
    echo "💡 Environment variables have been added to your shell config."
    echo "   You may need to restart your terminal or run:"
    echo "   source ~/.bashrc"
    echo
}

# Run main function
main "$@"